<?php

namespace App\Http\Controllers;

use App\Discussion;
use App\Models\Category;
use App\Models\Tag;
use App\ZL\Markdown\Markdown;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use EndaEditor;

class PostsController extends Controller
{
    protected $markdown;

    public function __construct(Markdown $markdown)
    {
        $this->middleware('auth',['only'=>['create','store','edit','update']]);
        $this->markdown =  $markdown;
    }

    public function index(Request $request){
        $tag = $request->get('tag');
        $category = $request->get('category');
        $discussions = false;
        if($tag)
            $discussions = Tag::find($tag)->discussions()->paginate(10);
        if($category)
            $discussions = Category::find($category)->discussions()->paginate(10);
        if(!$discussions)
            $discussions = Discussion::latest()->paginate(10);
        return view('forum.index',compact('discussions'));
    }

    public function show($id){
        $discussion = Discussion::findOrFail($id);
        $html = $this->markdown->markdown($discussion->body);
        return view('forum.show',compact('discussion','html'));
    }

    public function create()
    {
        return view('forum.create');
    }

    public function store(Requests\StoreDiscussionPostRequest $request)
    {
//        dd($request);
        $discussion = Discussion::create([
            'title'=>$request->get('title'),
            'body'=>$request->get('body'),
            'user_id'=>\Auth::user()->id,
            'last_user_id'=>\Auth::user()->id,
        ]);
        if($categories = $request->get('category_id'))
            $discussion->categories()->attach($categories);
        if($tags = $request->get('tag_id'))
            $discussion->tags()->attach($tags);
        return redirect()->action('PostsController@show',['id'=>$discussion->id]);
    }

    public function edit($id)
    {
        $discussion = Discussion::findOrFail($id);
        if(Auth::user()->id != $discussion->user_id) {
            return redirect('/');
        }
        return view('forum.edit',compact('discussion'));
    }

    public function update(Requests\StoreDiscussionPostRequest $request,$id)
    {
        $discussion = Discussion::findOrFail($id);
        $discussion->update($request->all());
        if($categories = $request->get('category_id')) {
            $discussion->categories()->detach();
            $discussion->categories()->attach($categories);
        }
        if($tags = $request->get('tag_id')) {
            $discussion->tags()->detach();
            $discussion->tags()->attach($tags);
        }
        return redirect()->action('PostsController@show',['id'=>$discussion->id]);
    }

    public function upload()
    {
        // endaEdit 为你 public 下的目录 update 2015-05-19
        $data = EndaEditor::uploadImgFile('uploads');

        return json_encode($data);
    }
}
